package com.mms.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {
	// 这是一个静态单例
	private static SqlSessionFactory sqlSessionFactory;

	// 在MyBatisUtils类被JVM加载时，static代码块仅执行一次
	static {
		try {
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 当业务层调用Mapper的方法时，先调用这个openSession方法，获取SqlSession
	public static SqlSession openSession() {
		return sqlSessionFactory.openSession();
	}

}
